﻿using System;
using System.Linq;
using System.Web.Mvc;
using NHibernate;
using Web.DataAccess;
using Web.HelperClasses;
using Web.Model;

namespace Web.Controllers
{
    public class NotificationController : Controller
    {

		public ActionResult SendAll()
        {
            if (!Request.ServerVariables["REMOTE_HOST"].StartsWith("10.")) 
                throw new UnauthorizedAccessException("Only server can access massmail actions");
			NotificationSender sender = new NotificationSender("goodworx@yandex.ru", session);
			//NotificationSender sender = new NotificationSender("admin@goodworx.ru", session);
            sender.SendAll();
            return View("OKView");

        }

        public ActionResult NotifyUpcomingProjects()
        {
            if (!Request.ServerVariables["REMOTE_HOST"].StartsWith("10."))
                throw new UnauthorizedAccessException("Only server can access massmail actions");
            var projects = new UpcomingProjectsQuery(null).Load(session)
                            .Where(p => 
                                    p.Beginning > DateTime.Now.AddDays(1).Date
                                    &&
                                    p.Beginning < DateTime.Now.AddDays(2).Date);
            
            foreach (Project project in projects) {
                ProjectNotifier notifier = new ProjectNotifier(project, session);
                notifier.NotifyUpсoming();
            }

            return View("OKView");
        }

        //[HttpGet]
        //public ActionResult AddOne()
        //{
        //    var newOne = new Notification()
        //    {
        //        Email = "alexandr.v.golubev@gmail.com",
        //        Body = "GoodWorx test",
        //        Subject = "Subject"
        //    };
        //    session.Save(newOne);

        //    return View();
        //}

        public NotificationController(ISession session)
        {
            this.session = session;
        }

		readonly ISession session;

    }
}
